package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    public void saveOrUpdate(StrategyComment comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            //如果没有id  说明是新增操作
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    public Page findAll() {
        Query query = new Query();
        long total = template.count(query, StrategyComment.class);
        Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime");
        query.with(pageable);
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list, pageable, total);
    }

    public Page query(StrategyCommentQuery qo) {
        Query query = new Query();
        //查询指定攻略明细的评论
        if (qo.getDetailId() != -1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //注意  此时total为指定明细的所有评论  所以不能有分页条件
        long total = template.count(query, StrategyComment.class);
        //分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        List<StrategyComment> list = template.find(query, StrategyComment.class);

        return new PageImpl(list, pageable, total);
    }

    //点赞 与取消点赞的实现类  调用的是mongodb
    public void thumbUp(String toid, Long userId) {
        StrategyComment comment = template.findById(toid, StrategyComment.class);
        List<Long> list = comment.getThumbuplist();//获取指定文章的点赞集合
        //判断当用点赞的用户是否在点赞的集合中
        if (list.contains(userId)) {
            //如果在 , 说明是取消点赞的操作
            comment.setThumbupnum(comment.getThumbupnum() - 1);//点赞总数减少一
            list.remove(userId); //取消点赞后 , 将该用户从集合中移除
        } else {
            //如果不在  说明是点赞的操作
            comment.setThumbupnum(comment.getThumbupnum() + 1);//总数加1
            list.add(userId);//将该用户加入集合中
        }
        //注意 , 操作完毕之后 , 需要更新到MongoDB的数据库中
        repository.save(comment);
    }


}
